const bcrypt = require('bcryptjs')
const {getUserInfo} = require('../service/user.service')
const {userFormatError,
     userAlreadyExists,
     userDoesNotExist, 
     userRegisterError,
     userLoginError,
     invalidPassword} = require('../constant/error.type')
const userValidator = async (ctx, next) => {
    const {user_name, password} = ctx.request.body
    if (!user_name || !password) {
        console.error('用户名或密码为空', ctx.request.body);
        ctx.app.emit('error', {userFormatError}, ctx)
        return 
    }

    await next()
}

const verifyUser = async (ctx, next) => {
    const {user_name} = ctx.request.body

    // if (await getUserInfo({ user_name })) {
    //     ctx.app.emit('error', userAlreadyExists, ctx)
    //     return 
    // }
    try {
        const res = await getUserInfo({user_name})
        if (res) {
            console.error('用户名已经存在', {user_name});
            ctx.app.emit('error', userAlreadyExists, ctx)
            return   
        }
    } catch(err) {
        console.error('获取用户信息错误', err);
        ctx.app.emit('error', userRegisterError, ctx)
        return
    }

    await next()
}

const cryptPassword = async (ctx, next) => {
    const { password } = ctx.request.body
    // 加盐
    const salt = bcrypt.genSaltSync(10);
    // 得到加密后的结果
    const hash = bcrypt.hashSync(password, salt)

    ctx.request.body.password = hash

    await next()
}

const verifyLogin = async (ctx, next) => {
    // 1.根据用户名去查数据库
    const {user_name, password} = ctx.request.body
    try {
        const res = await getUserInfo({user_name})
        
        if (!res) {
            console.error('用户名不存在', {user_name});
            ctx.app.emit('error', userDoesNotExist, ctx)
            return 
         }
          // 2.比对密码是否匹配
        if (!bcrypt.compareSync(password, res.password)) {
            ctx.app.emit('error', invalidPassword, ctx)
            return
        } 
    } catch (err) {
        console.error(err);
        ctx.app.emit('error', userLoginError, ctx)
        return
    }
    // 执行下一个中间件
    await next()
}
module.exports = {
    userValidator,
    verifyUser,
    cryptPassword,
    verifyLogin
}